package com.hanbang.gycatering.aboutme;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import com.hanbang.gangyu.R;
import com.hanbang.gycatering.application.MyApplication;
import com.hanbang.gycatering.photo.ClipLayout;
import com.hanbang.gycatering.utils.BitmapUtil;
import com.hanbang.gycatering.utils.HttpInterfaces;
import com.hanbang.gycatering.utils.MyRequestCallBack;
import com.hanbang.gycatering.utils.MyToast;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ClipPhotoActivity extends Activity {
	private ClipLayout clipLayout = null;
	// 照片存储路径
	private String filepath = "";
	// 拍完照存放的名称
	private String camera = "capture.jpg";
	private String clipPath = "clip.jpg";
	private String m = "";
	private String p = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.clip_photo);
		m = getIntent().getStringExtra("m");
		p = getIntent().getStringExtra("p");
		filepath = MyApplication.picFilepath;
		initView();
		getIntentData();
	}

	private void initView() {
		((TextView) findViewById(R.id.top_bar_title)).setText("头像裁剪");
		ImageView iv = (ImageView) findViewById(R.id.top_bar_left_image);
		iv.setVisibility(View.VISIBLE);
		iv.setOnClickListener(myOncClickListener);
		findViewById(R.id.ok).setOnClickListener(myOncClickListener);

		clipLayout = (ClipLayout) findViewById(R.id.clipLayout);
		clipLayout.setBorderColor(0xffff0000);
		clipLayout.setBorderShape(ClipLayout.ROUND);
		clipLayout.setClipPadding(50);
		clipLayout.setBorderWidth(2);
	}

	private OnClickListener myOncClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.top_bar_left_image:
				finish();
				break;
			case R.id.ok:
				saveBitmap();
				break;
			default:
				break;
			}
		}
	};

	/*
	 * 保存图片 先上传到服务器 成功了就保存到本地
	 */
	private void saveBitmap() {
		Bitmap bitmap = clipLayout.clip();
		if (bitmap != null) {
			String path = saveToSd(bitmap, clipPath);
			if (bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
			if (path != null && !path.equals("")) {
				saveService(path);
			}
		} else {
			// 失败
			setResult(1001);
			finish();
		}
	}

	private void saveService(String path) {
		File f = new File(path);
		if (f.exists()) {
			RequestParams params = new RequestParams();
			params.addBodyParameter("action", "head");
			params.addBodyParameter("userphone", m);
			params.addBodyParameter("password", p);
			params.addBodyParameter("Filedata", f);
			((MyApplication) getApplicationContext()).httpUtils.send(
					HttpMethod.POST, HttpInterfaces.ORG_POST, params,
					new MyRequestCallBack<String>(this,
							getString(R.string.loadding)) {
						@Override
						public void onFailure(HttpException error, String msg) {
							super.onFailure(error, msg);
							// 失败
							setResult(1001);
							finish();
						}

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							super.onSuccess(responseInfo);
							try {
								JSONObject json = new JSONObject(
										responseInfo.result);
								if(json.getInt("state")==1){
									String path = json.getString("path");
									Intent intent = new Intent();
									intent.putExtra("path", path);
									setResult(1000, intent);
								}

								finish();
							} catch (JSONException e) {
								e.printStackTrace();
								// 失败
								setResult(1001);
								finish();
							}
						}
					});
		}

	}

	private void getIntentData() {
		new Handler().postDelayed(new Runnable() {
			public void run() {
				// execute the task]
				try {
					// 获取图片路径
					String picturePath = null;
					// 相册
					if (1 == getIntent().getIntExtra("type", 0)) {
						Uri uri = getIntent().getData();
						picturePath = getPath(ClipPhotoActivity.this, uri);
					}
					// 拍照
					else if (2 == getIntent().getIntExtra("type", 0)){
						File fDir = new File(filepath);
						if (!fDir.exists()) {
							fDir.mkdirs();
						}
						File cameraFile = new File(fDir, camera);
						picturePath = cameraFile.getPath();
					}
					if (picturePath != null) {
						@SuppressWarnings("deprecation")
						Bitmap bitmap = BitmapUtil.decodeFile(new File(
								picturePath), getWindowManager()
								.getDefaultDisplay().getWidth(),
								getWindowManager().getDefaultDisplay()
										.getHeight());
						clipLayout.setClipPhoto(bitmap);
						clipLayout.show();
					} else {
						MyToast.show(ClipPhotoActivity.this, "获取照片失败！",
								Toast.LENGTH_SHORT);
					}
				} catch (Exception e) {
					e.printStackTrace();
					MyToast.show(ClipPhotoActivity.this, "获取照片失败！",
							Toast.LENGTH_SHORT);
					finish();
				}

			}
		}, 30);// 30毫秒用于等待解码图片，要对唱时间可以自己设置
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	/*
	 * 保存到本地，当保存到服务器成功的时候就保存到本地 不成功就不保存
	 */
	private String saveToSd(Bitmap bitmap, String name) {
		// 先创建文件路径，应为创建文件的时候前提是文件路径存在
		File path = new File(filepath);
		File file = null;
		if (path.exists() || path.mkdirs()) {
			Log.e("mkdirs", path.getPath());
			// 创建保存的图片名称
			file = new File(path, name);
			if (!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
					return "";
				}
			}
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		} finally {
			if (fos != null) {
				try {
					fos.flush();
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				fos = null;
			}
		}
		return file.getPath();
	}

	@SuppressLint("NewApi")
	public String getPath(Context context, Uri uri) {

		// DocumentProvider
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT
				&& DocumentsContract.isDocumentUri(context, uri)) {
			// ExternalStorageProvider
			if (isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];
				Log.e("ssssss", "DocumentProvider");
				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/"
							+ split[1];
				}
				// TODO handle non-primary volumes
			}
			// DownloadsProvider
			else if (isDownloadsDocument(uri)) {

				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(
						Uri.parse("content://downloads/public_downloads"),
						Long.valueOf(id));
				Log.e("ssssss", "DownloadsProvider");
				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				final String selection = "_id=?";
				final String[] selectionArgs = new String[] { split[1] };

				Log.e("ssssss", "isMediaDocument");
				return getDataColumn(context, contentUri, selection,
						selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme())) {
			Log.e("ssssss", "content");
			// Return the remote address
			if (isGooglePhotosUri(uri)) {

				return uri.getLastPathSegment();
			}

			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			Log.e("ssssss", "file");
			return uri.getPath();
		}

		return null;
	}

	public String getDataColumn(Context context, Uri uri, String selection,
			String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = { column };

		try {
			cursor = context.getContentResolver().query(uri, projection,
					selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				final int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	public boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri
				.getAuthority());
	}

	public boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri
				.getAuthority());
	}

	public boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri
				.getAuthority());
	}

	public boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri
				.getAuthority());
	}
}